package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static TextView tv_progress, tv_total;
    private static SeekBar sb;
    private Intent intent;
    private MyServiceConn conn;
    private ObjectAnimator animator;
    private MusicService.MusicControl musicControl;
    private boolean isUnbind = false;  //记录服务是否解绑

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    private void init() {
        tv_progress = findViewById(R.id.tv_progress);
        tv_total = findViewById(R.id.tv_total);
        sb = findViewById(R.id.sb);
        findViewById(R.id.btn_play).setOnClickListener(this);
        findViewById(R.id.btn_pause).setOnClickListener(this);
        findViewById(R.id.btn_continue_play).setOnClickListener(this);
        findViewById(R.id.btn_exit).setOnClickListener(this);

        intent = new Intent(MainActivity.this, MusicService.class);  //创建意图对象
        conn = new MyServiceConn();  //创建服务连接对象
        bindService(intent, conn, BIND_AUTO_CREATE);   //绑定服务
        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {  //滑动条进度改变时，会调用此方法
                if (progress == seekBar.getMax()) {   //当滑动条滑倒末端时结束动画
                    animator.pause();  //停止播放动画
                }
            }

            //滑动条开始滑动时调用
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            //滑动条停止滑动时调用
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //根据拖动的进展改变音乐播放进度
                int progress = seekBar.getProgress();  //获取seekBar的进展
                musicControl.seekTo(progress);   //改变播放进展
            }
        });

        ImageView iv_music = findViewById(R.id.iv_music);

        animator = ObjectAnimator.ofFloat(iv_music, "rotation", 0f, 360.0f);
        animator.setDuration(10000);  //动画旋转一周为10秒
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(-1);  //-1表示设置动画无限循环

    }

    public static Handler handler = new Handler() {  //创建消息处理器对象

        //从主线程中处理子线程发送的消息
        @Override
        public void handleMessage(@NonNull Message msg) {
            Bundle bundle = msg.getData();  //获取子线程的消息
            int duration = bundle.getInt("duration");  //歌曲的总时长
            //歌曲当前进度
            int currentPosition = bundle.getInt("currentPosition");

            sb.setMax(duration);  //设置seekBar的最大值为歌曲的总时长

            sb.setProgress(currentPosition);  //设置seekBar当前的进度位置

            int minute = duration / 1000 / 60;
            int second = duration / 1000 % 60;

            String strMinute = null;
            String strSecond = null;

            if (minute < 10) {   //如果歌曲的时间中的分钟小于10
                strMinute = "0" + minute;  //在分钟前面加一个0
            } else {
                strMinute = minute + "";
            }

            if (second < 10) {
                strSecond = "0" + second;
            } else {
                strSecond = second + "";
            }

            tv_total.setText(strMinute + ":" + strSecond);

            minute = currentPosition / 1000 / 60;
            second = currentPosition / 1000 % 60;
            if (minute < 10) {
                strMinute = "0" + minute;
            } else {
                strMinute = minute + "";
            }

            if (second < 10) {
                strSecond = "0" + second;
            } else {
                strSecond = second + "";
            }

            tv_progress.setText(strMinute + ":" + strSecond);
        }
    };


    class MyServiceConn implements ServiceConnection {  //用于实现连接服务


        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicControl = (MusicService.MusicControl) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    private void unbind(boolean isUnbind) {
        if (!isUnbind) {  //判断服务是否解绑
            unbindService(conn);  //解绑服务
            stopService(intent);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_play:
                Intent intent = getIntent();
                String musicPath = intent.getStringExtra("musicPath");
                musicControl.play(musicPath);
                animator.start();
                break;
            case R.id.btn_pause:
                musicControl.pausePlay();
                animator.pause();
                break;
            case R.id.btn_continue_play:
                musicControl.continuePlay();
                animator.start();
                break;
            case R.id.btn_exit:
                unbind(isUnbind);
                isUnbind = true;
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbind(isUnbind);
    }
}


